<template>
  <div class="detail" ref="containerRef">
    <a-affix :target="(containerRef as HTMLElement)">
      <a-page-header :title="modleId ? '编辑模板' : '创建模板'" @back="back" class="head"> </a-page-header>
    </a-affix>

    <div class="form-content">
      <a-form ref="formRef" :model="form" :style="{ width: '800px' }" @submit="handleSubmit">
        <a-form-item field="type" label="模板类别" :rules="rules.type">
          <a-select @popup-visible-change="getStatusOption" v-model="form.type" placeholder="请选择类别" allow-clear>
            <a-option v-for="item in statusOption" :key="item.id" :value="item.id">{{ item.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="type" label="复用模板">
          <a-select
            allow-search
            @change="handleChangeModel"
            @popup-visible-change="getModelOption"
            placeholder="请选择"
            allow-clear
          >
            <a-option v-for="item in modleOption" :key="item.id" :value="item.id">{{ item.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="name" label="模板名称" :rules="rules.name">
          <a-input v-model="form.name" placeholder="请输入需求名称" allow-clear />
        </a-form-item>
        <a-form-item field="desc" label="模板描述" :rules="rules.desc">
          <a-textarea auto-size v-model="form.desc" placeholder="请输入描述信息" allow-clear />
        </a-form-item>
        <a-form-item field="model" label="模型选择" :rules="rules.model">
          <a-select v-model="form.model" @popup-visible-change="getModelOption2" placeholder="请选择" allow-clear>
            <a-option v-for="item in modleOption2" :key="item.id" :value="item.id">{{ item.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="push_system" label="推送平台" :rules="rules.push_system">
          <a-cascader :options="pushSystemOptions" v-model="form.push_system" placeholder="请选择" allow-clear />
        </a-form-item>
        <a-form-item v-if="form.type == 2" field="source_code" label="数据来源" :rules="rules.source_code">
          <a-select v-model="form.source_code" placeholder="请选择" allow-clear>
            <a-option v-for="item in source_codeOption" :key="item.value" :value="item.value">{{
              item.label
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="prompt" label="AI提示词">
          <a-textarea
            auto-size
            v-model="form.prompt"
            :placeholder="`请输入通用提示词，#${form.type == 1 ? 'title' : '文章'}#代表插入文章位置`"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="filters" label="过滤词板">
          <a-textarea auto-size v-model="form.filters" placeholder="请输入，多个过滤词，中间用、号隔开" allow-clear />
        </a-form-item>
        <a-form-item field="replaces" label="替换词板">
          <a-radio-group v-model="form.replaces">
            <a-radio :value="0">无</a-radio>
            <a-radio :value="1">有</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-space style="margin: 0 0 20px 167px" v-if="form.replaces == 1">
          <a-table size="small" :data="placedata" :pagination="false">
            <template #columns>
              <a-table-column title="原文" data-index="old">
                <template #cell="{ record }">
                  <a-input size="small" placeholder="请输入" v-model="record.old" allow-clear />
                </template>
              </a-table-column>
              <a-table-column title="替换成" data-index="new">
                <template #cell="{ record }">
                  <a-input size="small" placeholder="请输入" v-model="record.new" allow-clear />
                </template>
              </a-table-column>
              <a-table-column title="" data-index="" align="left" :width="80">
                <template #cell="{ record, rowIndex }">
                  <icon-minus-circle-fill
                    style="margin-right: 10px; cursor: pointer; color: #f53f3f"
                    :size="18"
                    v-if="rowIndex !== 0"
                    @click="handleSubPlace(rowIndex)"
                  />
                  <icon-plus-circle-fill style="cursor: pointer; color: #168cff" :size="18" @click="handleAddPlace" />
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-space>
        <a-form-item field="img_switch" label="是否配图">
          <a-radio-group v-model="form.img_switch">
            <a-radio :value="0">否</a-radio>
            <a-radio :value="1">是</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-if="form.type != 2" field="local_switch" label="是否参考本地数据库">
          <a-radio-group v-model="form.local_switch">
            <a-radio :value="0">否</a-radio>
            <a-radio :value="1">是</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="status" label="模板状态">
          <a-switch v-model="form.status" :checked-value="1" :unchecked-value="0" />
        </a-form-item>
      </a-form>
      <a-space style="justify-content: center; margin-bottom: 10px">
        <a-button @click="back">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确认</a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts" name="DataDetail">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePagination } from '@/hooks'
import { Message } from '@arco-design/web-vue'
import { getStatusOptions, getTemplateList, getPushSystem, getTemplateDetail, addTemplate, editTemplate } from '@/apis'
const route = useRoute()
const router = useRouter()
const modleId = ref(route.query.id)
const formRef = ref<any>()
// 替换词板
const placedata = ref([{ old: '', new: '' }])
// 获取模板列表
const modleOption = ref([])
const getModelOption = async (visible) => {
  if (!visible) return
  const resData = await getTemplateList({
    page: 1,
    pagesize: 1000,
    type: form.type
  }).then((res) => {
    modleOption.value = res.data.data || []
  })
}
// 树形遍历
function transformTree(data) {
  return data.map((node) => ({
    value: node.id,
    label: node.name,
    children: node?.child?.length > 0 ? transformTree(node.child) : null
  }))
}
// 获取模型列表
const modleOption2 = ref([])
const pushSystemOptions = ref([]) //推送平台
let system_channel = [] //推送品台
const getModelOption2 = async (visible) => {
  if (!visible) return
  await getPushSystem({
    page: 1,
    pagesize: 1000
  }).then((res) => {
    modleOption2.value = res.data.model || []
    // 推送品台处理
    system_channel = res.data.system_channel || []
    pushSystemOptions.value = res.data.push_system.map((dd) => {
      let isHave = system_channel.findIndex((cc) => cc.push_system_id === dd.id)
      let children = null
      if (isHave !== -1) {
        let temp = system_channel.filter((cc) => cc.push_system_id === dd.id)
        children = transformTree(temp)
      }
      return {
        value: dd.id,
        label: dd.name,
        children
      }
    })
    console.log(pushSystemOptions.value)
  })
}
const handleChooseModel = async (id) => {
  if (id) {
    let res = await getTemplateDetail({ template_id: id })
    if (res.code === 1) {
      let curData = res.data
      form.type = +curData.type
      form.name = curData.name
      form.desc = curData.desc
      form.model = +curData.model
      form.push_system = curData.system_channel_id ?? curData.push_system
      form.prompt = curData.prompt
      form.filters = curData.filters
      form.img_switch = curData.img_switch
      form.local_switch = curData.local_switch
      form.status = curData.status
      form.source_code = curData?.source_code || ''

      if (curData.replaces && curData.replaces !== '"0"') {
        try {
          form.replaces = 1

          let temp = JSON.parse(curData.replaces)
          placedata.value = temp
        } catch {
          form.replaces = 0

          console.log('替换词板数据格式错误')
        }
      } else {
        form.replaces = 0
      }
    } else {
      Message.error(res.msg)
    }
  }
}
const handleChangeModel = (val) => {
  handleChooseModel(val)
}
getModelOption2(true)
// 获取状态下拉
const statusOption = ref([])
const getStatusOption = async (visible) => {
  if (!visible) return
  let res = await getStatusOptions()
  if (res.code == 1) {
    statusOption.value = res.data.type || []
  }
  console.log(statusOption.value)
}
getStatusOption(true)
const dateRangeFormat = (dates: any) => {
  return `${dates[0].format('YYYY-MM-DD')} ~ ${dates[1].format('YYYY月MM-DD')}`
}
const loading = ref(false)
const containerRef = ref<HTMLElement | null>()
const form = reactive({
  type: '',
  name: '',
  desc: '',
  model: '',
  push_system: '',
  prompt: '',
  filters: '',
  replaces: 0,
  img_switch: 0,
  local_switch: 0,
  status: 1,
  source_code: ''
})
const source_codeOption = [
  {
    label: '游民星空/PC/资讯新闻',
    value: '游民星空/PC/资讯新闻'
  },
  {
    label: '3DM/PC/资讯新闻',
    value: '3DM/PC/资讯新闻'
  },
  {
    label: '17173/PC/资讯新闻',
    value: '17173/PC/资讯新闻'
  },
  {
    label: '游戏基因/PC/资讯新闻',
    value: '游戏基因/PC/资讯新闻'
  },
  {
    label: '游戏早知道/PC/资讯新闻',
    value: '游戏早知道/PC/资讯新闻'
  },
  {
    label: '叶子猪/PC/资讯新闻',
    value: '叶子猪/PC/资讯新闻'
  },
  {
    label: '4Gamers/PC/资讯新闻',
    value: '4Gamers/PC/资讯新闻'
  },
  {
    label: '游戏茶馆/PC/资讯新闻',
    value: '游戏茶馆/PC/资讯新闻'
  },
  {
    label: '游戏日报/PC/资讯新闻',
    value: '游戏日报/PC/资讯新闻'
  },
  {
    label: 'IGN/PC/资讯新闻',
    value: 'IGN/PC/资讯新闻'
  },
  {
    label: '好游快爆/手游/资讯新闻',
    value: '好游快爆/手游/资讯新闻'
  },
  {
    label: '游戏基地/手游/资讯新闻',
    value: '游戏基地/手游/资讯新闻'
  },
  {
    label: '游民星空/攻略/游戏攻略',
    value: '游民星空/攻略/游戏攻略'
  },
  {
    label: '游侠网/攻略/游戏攻略',
    value: '游侠网/攻略/游戏攻略'
  },
  {
    label: '太平洋科技/设备/游戏设备',
    value: '太平洋科技/设备/游戏设备'
  },
  {
    label: '3DM/设备/游戏设备',
    value: '3DM/设备/游戏设备'
  }
]
const rules = {
  type: [{ required: true, message: '模板类别不能为空' }],
  name: [{ required: true, message: '模板名称不能为空' }],
  desc: [{ required: true, message: '模板描述不能为空' }],
  source_code: [{ required: true, message: '数据来源不能为空' }],
  model: [{ required: true, message: '模型必选' }],
  push_system: [{ required: true, message: '推送平台不能为空' }]
}
const back = () => {
  router.back()
}
const resetForm = () => {
  formRef.value?.resetFields()
}

function findNodeById(nodes, id) {
  // 遍历所有根节点
  for (let node of nodes) {
    const result = findNodeInTree(node, id)
    if (result) {
      return result
    }
  }
  // 如果没有找到匹配的节点，返回 null
  return null
}

function findNodeInTree(node, id) {
  // 如果当前节点的 ID 匹配，返回当前节点
  if (node.id === id) {
    return node
  }

  // 如果当前节点有子节点，则递归查找每个子节点
  if (node.child) {
    for (let child of node.child) {
      const result = findNodeInTree(child, id)
      if (result) {
        return result
      }
    }
  }

  // 如果没有找到匹配的节点，返回 null
  return null
}
// 确认保存
const handleSubmit = async () => {
  const flag = await formRef.value?.validate()
  if (flag) return false
  let curTreeDate = findNodeById(system_channel, form.push_system)
  let params = {
    ...form,
    system_channel_id: form.push_system,
    push_system: curTreeDate.push_system_id
  }
  // 如果是资讯不要参考本地数据库
  if (form.type === 2) {
    params.local_switch = null
  }
  if (form.replaces == '1') {
    params.replaces = placedata.value
    params.source_code = ''
  }
  let res
  if (modleId.value) {
    res = await editTemplate({
      ...params,
      template_id: modleId.value
    })
  } else {
    res = await addTemplate(params)
  }
  if (res.code === 1) {
    Message.success(res.msg)
    setTimeout(() => {
      router.push('/template-management')
      formRef.value?.resetFields()
    }, 500)
  } else {
    let errorText = (modleId.value ? '编辑' : '创建') + '失败'
    Message.error(res.msg || errorText)
  }
}

const columns = [
  {
    title: '原文',
    dataIndex: 'old'
  },
  {
    title: '替换成',
    dataIndex: 'new'
  }
]
const data = reactive([
  {
    key: '1',
    old: 'Jane Doe',
    new: '32 Park Road, London'
  },
  {
    key: '2',
    old: 'Alisa Ross',
    new: '35 Park Road, London'
  }
])
const handleAddPlace = () => {
  placedata.value.push({ old: '', new: '' })
}
const handleSubPlace = (index) => {
  placedata.value.splice(index, 1)
}
if (modleId.value) {
  handleChooseModel(modleId.value)
}
</script>

<style lang="scss" scoped>
.detail {
  overflow: auto;
  height: 100%;
  // display: flex;
  // flex-direction: column;
  .head {
    background: var(--color-bg-1);
  }
  .item {
    margin: $margin;
    background: var(--color-bg-1);
    border-radius: 2px;
  }
  .form-content {
    // flex: 1;
    overflow: hidden;
    margin: $margin;
    background: var(--color-bg-1);
    padding: $padding;
    padding-bottom: 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
  }
}
</style>
